const app = getApp();
const api = require('./api.js');
const core = require('./core.js');
function scopeLogin() {
  return new Promise((resolve, reject) => {
    let apicontent = api.members.loginByWeixin()
    wx.login({
      success: function(ret) {
        if (ret.code) {
          app.setCache("code",ret.code)
          wx.getUserInfo({
            lang: 'zh_CN',
            success(res2) {
              console.log(res2)
              core.post(apicontent, {
                code: ret.code,
                encryptedData: res2.encryptedData,
                iv: res2.iv,
                userInfos: JSON.stringify(res2.userInfo),
                signature: res2.signature,
                shopId: app.globalData.shopId
              }, function(login_res) {
                if (login_res.code == 1) {
                  let data = login_res.data
                  app.setCache('userinfo', data.userInfo);
                  app.setCache('userinfo_id', data.userInfo.id);
                  let currentPage = '/' + app.getCache('currentUrl') + '_' + 'auth'
                  app.setCache('currentUrl', currentPage)
                  app.setCache("userInfo", data.userInfo)
                  app.setCache("mobile", data.userInfo.mobile)
                  // 设置统计代码的openid
                  app.matomo.setUserId(data.userInfo.openid)
                  app.sr.setUser({
                    open_id: data.userInfo.openid,
                    union_id:data.userInfo.unionid                    
                  })
                  core.getToken((resT) => {
                    if (resT == "success") {
                      app.setCache('tokennum', '0')
                      resolve(true);
                    } else {
                      scopeLogin();
                    }
                  });
                } else {
                  core.alert('获取用户登录态失败:' + login_res.message);
                  resolve(false);
                }
              })
            }
          })
        }
      },
      fail: function() {
        core.alert('获取用户信息失败!');
        reject(false);
      }
    })
  })
}
module.exports = {
  scopeLogin
}